import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import 'package:lmmi/common/index.dart';

// 订阅选项数据模型
class SubscriptionOption {
  final String id;
  final String displayName;
  final String price;
  final String duration;
  final String description;

  SubscriptionOption({
    required this.id,
    required this.displayName,
    required this.price,
    required this.duration,
    required this.description,
  });
}

class SubscribePage extends ConsumerStatefulWidget {
  const SubscribePage({super.key});

  @override
  ConsumerState<SubscribePage> createState() => _SubscribePageState();
}

class _SubscribePageState extends ConsumerState<SubscribePage> {
  int selectedIndex = 1; // 默认选中第二个选项（1月）
  bool _isLoading = false;
  PurchaseManager? _purchaseManager;

  // 订阅选项数据
  final List<SubscriptionOption> subscriptionOptions = [
    SubscriptionOption(
      id: 'com.lmmi.ios.vip.wk.9_99',
      displayName: 'Premium (1w.)',
      price: '\$9.99',
      duration: '(1w.)',
      description: '订阅产品 一周时限',
    ),
    SubscriptionOption(
      id: 'com.lmmi.ios.vip.mo.19_99',
      displayName: 'Premium (1m.)',
      price: '\$19.99',
      duration: '(1m.)',
      description: '订阅产品 一月时限',
    ),
    SubscriptionOption(
      id: 'com.lmmi.ios.vip.qtr.29_99',
      displayName: 'Premium (3m.)',
      price: '\$29.99',
      duration: '(3m.)',
      description: '订阅产品 三月时限',
    ),
    SubscriptionOption(
      id: 'com.lmmi.ios.vip.ann.69_99',
      displayName: 'Premium (1y.)',
      price: '\$69.99',
      duration: '(1y.)',
      description: '订阅产品 一年时限',
    ),
  ];

  @override
  void initState() {
    super.initState();
    _initializePurchaseManager();
  }

  @override
  void dispose() {
    // 页面关闭时刷新用户状态，确保返回到其他页面时状态是最新的
    if (mounted) {
      ref.read(userProvider.notifier).forceRefreshUserState();
    }
    super.dispose();
  }

  // 初始化内购管理器
  Future<void> _initializePurchaseManager() async {
    _purchaseManager = PurchaseManager();
    await _purchaseManager!.initialize();

    // 设置用户状态更新回调
    _purchaseManager!.setUserStateUpdateCallback(() {
      // 强制刷新用户状态，确保所有相关Provider都更新
      if (mounted) {
        ref.read(userProvider.notifier).forceRefreshUserState();
      }
    });
  }

  // 处理购买
  Future<void> _handlePurchase() async {
    if (_purchaseManager == null) {
      _showMessage('Purchase service not initialized');
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final selectedOption = subscriptionOptions[selectedIndex];
      final success = await _purchaseManager!.buyProduct(selectedOption.id);

      if (success) {
        _showMessage('Purchase initiated successfully');
      } else {
        _showMessage('Failed to initiate purchase');
      }
    } catch (e) {
      _showMessage('Purchase error: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 处理恢复购买
  Future<void> _handleRestorePurchases() async {
    if (_purchaseManager == null) {
      _showMessage('Purchase service not initialized');
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final success = await _purchaseManager!.restorePurchases();

      if (success) {
        _showMessage('Restore purchases initiated');
      } else {
        _showMessage('Failed to restore purchases');
      }
    } catch (e) {
      _showMessage('Restore error: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 显示消息
  void _showMessage(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(message), duration: const Duration(seconds: 2)),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          onPressed: () {
            context.goBack();
          },
          icon: Icon(Icons.arrow_back_ios_new_rounded, color: Colors.white),
        ),
        actions: [
          GestureDetector(
            onTap: _isLoading ? null : _handleRestorePurchases,
            child: Padding(
              padding: EdgeInsets.only(right: 16.w),
              child: Text(
                'Restore Purchases',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontFamily: 'inter',
                  fontWeight: FontWeight.w400,
                  height: 1.29.h,
                  decoration: TextDecoration.underline,
                  decorationColor: Colors.white,
                  decorationThickness: 0.9.h,
                  decorationStyle: TextDecorationStyle.solid,
                ),
              ),
            ),
          ),
        ],
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.homeBg),
            fit: BoxFit.fill,
          ),
        ),
        child: Stack(
          children: [
            Positioned(
              top: 75.h,
              right: 0,
              child: Image.asset(
                MyImages.subBg,
                width: 342.w,
                height: 342.h,
                fit: BoxFit.contain,
              ),
            ),

            // 订阅内容
            Positioned(
              top: 425.h,
              left: 0,
              right: 0,
              child: Column(
                children: [
                  _buildSubscribeContent(),
                  SizedBox(height: 20.h),
                  _buildSubscriptionOptions(),
                  // 购买按钮
                  SizedBox(height: 35.h),
                  GestureDetector(
                    onTap: _isLoading ? null : _handlePurchase,
                    child: Container(
                      width: 351.w,
                      height: 58.h,
                      decoration: ShapeDecoration(
                        gradient: LinearGradient(
                          begin: Alignment(0.00, 0.50),
                          end: Alignment(1.00, 0.50),
                          colors: [Color(0xFFFF8C00), Color(0xFFF8FFC7)],
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(60.r),
                        ),
                      ),
                      child: Center(
                        child: _isLoading
                            ? SizedBox(
                                width: 24.w,
                                height: 24.h,
                                child: CircularProgressIndicator(
                                  color: Colors.black,
                                  strokeWidth: 2,
                                ),
                              )
                            : Text(
                                'CONTINUE',
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16.sp,
                                  fontFamily: 'PingFang SC',
                                  fontWeight: FontWeight.w600,
                                  height: 1.12.h,
                                  letterSpacing: 0.23.sp,
                                ),
                              ),
                      ),
                    ),
                  ),
                  SizedBox(height: 10.h),
                  Text.rich(
                    TextSpan(
                      children: [
                        TextSpan(
                          text: 'By continuing, you agree to our',
                          style: TextStyle(
                            color: const Color(0xFFBABABA),
                            fontSize: 10.sp,
                            fontFamily: 'PingFang SC',
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                        TextSpan(
                          text: ' ',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 10.sp,
                            fontFamily: 'PingFang SC',
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                        TextSpan(
                          text: 'Terms of Service',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 10.sp,
                            fontFamily: 'PingFang SC',
                            fontWeight: FontWeight.w400,
                            decoration: TextDecoration.underline,
                          ),
                        ),
                        TextSpan(
                          text: ' ',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 10.sp,
                            fontFamily: 'PingFang SC',
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                        TextSpan(
                          text: 'and',
                          style: TextStyle(
                            color: const Color(0xFFBABABA),
                            fontSize: 10.sp,
                            fontFamily: 'PingFang SC',
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                        TextSpan(
                          text: ' ',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 10.sp,
                            fontFamily: 'PingFang SC',
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                        TextSpan(
                          text: 'EULA',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 10.sp,
                            fontFamily: 'PingFang SC',
                            fontWeight: FontWeight.w400,
                            decoration: TextDecoration.underline,
                          ),
                        ),
                      ],
                    ),
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSubscribeContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          'Become a Member',
          style: TextStyle(
            color: const Color(0xFFFF8C00),
            fontSize: 20.sp,
            fontFamily: 'port',
            fontWeight: FontWeight.w400,
            height: 1.29.h,
          ),
        ),
        IntrinsicWidth(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildSubscribeContentItem('View Previously Sent Letters'),
              _buildSubscribeContentItem('Unlimited Daily Recording'),
              _buildSubscribeContentItem('Membership Badge'),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildSubscribeContentItem(String text) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        SvgPicture.asset(MyIcons.right, width: 12.w, height: 12.h),
        SizedBox(width: 5.w),
        Text(
          text,
          style: TextStyle(
            color: Colors.white,
            fontSize: 12.sp,
            fontFamily: 'pingfang',
            fontWeight: FontWeight.w400,
            height: 1.29.h,
          ),
        ),
      ],
    );
  }

  // 构建订阅选项列表
  Widget _buildSubscriptionOptions() {
    return SizedBox(
      height: 116.h,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        itemCount: subscriptionOptions.length,
        itemBuilder: (context, index) {
          return Padding(
            padding: EdgeInsets.only(
              right: index < subscriptionOptions.length - 1 ? 12.w : 0,
            ),
            child: GestureDetector(
              onTap: () {
                setState(() {
                  selectedIndex = index;
                });
              },
              child: _buildSubscriptionCard(
                subscriptionOptions[index],
                index == selectedIndex,
              ),
            ),
          );
        },
      ),
    );
  }

  // 构建单个订阅卡片
  Widget _buildSubscriptionCard(SubscriptionOption option, bool isSelected) {
    return Container(
      width: 100.w,
      height: 116.h,
      decoration: ShapeDecoration(
        color: isSelected ? null : const Color(0xFFFAFAFA),
        gradient: isSelected
            ? const LinearGradient(
                begin: Alignment(0.50, -0.00),
                end: Alignment(0.50, 1.00),
                colors: [Color(0xFFFDA52A), Colors.white],
              )
            : null,
        shape: RoundedRectangleBorder(
          side: BorderSide(
            width: isSelected ? 3 : 1,
            color: isSelected
                ? const Color(0xFFFF8C00)
                : const Color(0xFFDBDBDB),
          ),
          borderRadius: BorderRadius.circular(10),
        ),
      ),
      child: Stack(
        children: [
          // 右上角标签
          Positioned(
            top: 0,
            right: 0,
            child: Container(
              width: isSelected ? 66.w : 67.w,
              height: 25.h,
              decoration: ShapeDecoration(
                color: isSelected
                    ? const Color(0xFFFF8C00)
                    : const Color(0xFFDBDBDB),
                shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(
                    topRight: Radius.circular(10),
                    bottomLeft: Radius.circular(14),
                  ),
                ),
              ),
              child: Center(
                child: Text(
                  'Premium',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12.sp,
                    fontFamily: 'PingFang SC',
                    fontWeight: FontWeight.w400,
                    height: 1.50,
                    letterSpacing: 0.23,
                  ),
                ),
              ),
            ),
          ),
          // 中间内容
          Positioned.fill(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(height: 12.h), // 为顶部标签留空间
                Text(
                  option.duration,
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 16.sp,
                    fontFamily: 'PingFang SC',
                    fontWeight: FontWeight.w400,
                    height: 1.12,
                    letterSpacing: 0.23,
                  ),
                ),
                SizedBox(height: 8.h),
                Text(
                  option.price,
                  style: TextStyle(
                    color: const Color(0xFFFF8C00),
                    fontSize: 20.sp,
                    fontFamily: 'PingFang SC',
                    fontWeight: FontWeight.w600,
                    height: 0.90,
                    letterSpacing: 0.23,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
